package cn.yuysaln.domain.strategy.service.rule.filter.impl;

import cn.yuysaln.domain.strategy.model.entity.RuleActionEntity;
import cn.yuysaln.domain.strategy.model.entity.RuleMatterEntity;
import cn.yuysaln.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.yuysaln.domain.strategy.repository.IStrategyRepository;
import cn.yuysaln.domain.strategy.service.annotation.LogicStrategy;
import cn.yuysaln.domain.strategy.service.rule.filter.ILogicFilter;
import cn.yuysaln.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import cn.yuysaln.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * 实现权重过滤
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_WIGHT)
public class RuleWeightLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Resource
    private IStrategyRepository repository;

    public Long userScore = 4500L; //模拟用户积分

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-权重范围 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());

        String userId = ruleMatterEntity.getUserId();
        Long strategyId = ruleMatterEntity.getStrategyId();
        Integer awardId = ruleMatterEntity.getAwardId();
        String ruleModel = ruleMatterEntity.getRuleModel();
        String ruleValue = repository.queryStrategyRuleValue(strategyId, awardId, ruleModel);
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);

        //如果没有配置权重或权重为空  直接放行
        if (null == analyticalValueGroup || analyticalValueGroup.isEmpty()) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                    .build();
        }

        //配置了权重，比较当前用户的积分在哪一档
        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys);
        //拿到档位
        Long nextValue = analyticalSortedKeys.stream().filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);

        //档位非空  接管
        if (null != nextValue) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                            .strategyId(strategyId)
                            .ruleWeightValueKey(analyticalValueGroup.get(nextValue))
                            .build())
                    .ruleModel(DefaultLogicFactory.LogicModel.RULE_WIGHT.getCode())
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                    .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                    .build();
        }

        //权重为空放行
        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();


    }


    /**
     * @param ruleValue 具体规则值 如：4000:102,103,104,105
     * @return 拆解为 4000  ---   4000:102,103,104,105   装入 Map返回
     */
    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();

        for (String ruleValueGroup : ruleValueGroups) {
            if (null == ruleValueGroup || ruleValueGroup.isEmpty()) {
                return ruleValueMap;
            }

            String[] parts = ruleValueGroup.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            }

            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueGroup);

        }
        return ruleValueMap;
    }

}
